package com.example.lenovo.weiyi;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.com.ruanmeng.demon.AddZanM;
import com.com.ruanmeng.demon.CommonM;
import com.com.ruanmeng.demon.LunTanXQM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.ImgDataUtil;
import com.com.ruanmeng.utils.Params;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.view.CircularImage;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import adapter.BaseLoadMoreHeaderAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

public class LunTanXQActivity extends BaseActivity {

    @BindView(R.id.rlist_ltxq)
    RecyclerView rlistLtxq;
    @BindView(R.id.refresh_ltxq)
    SwipeRefreshLayout refreshLtxq;
    @BindView(R.id.ed_ltxq_hf)
    EditText edLtxqHf;
    private LinearLayoutManager linearLayoutManager;
    ArrayList<LunTanXQM.ObjectBean.RepliesBean> Temp_list = new ArrayList<>();
    private PCXQAdapter mAdapter;
    private CircularImage imv_ltxq_userpic;
    private TextView tv_ltxq_name;
    private TextView tv_ltxq_dw;
    private TextView tv_ltxq_hfnum;
    private TextView tv_ltxq_content;
    private TextView tv_ltxq_time;
    private LinearLayout li_allhf;
    private int page = 1;
    private TextView tv_ltxq_null;
    private LinearLayout li_ltheader_allhf;
    private TextView tv_ltxq_title;
    private ImageView imvcollection;
    private String Is_collection;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lun_tan_xq);
        ButterKnife.bind(this);
        ChangLayTitle("论坛");
        ShowLayCollection();
        LayBack();
        Is_collection = getIntent().getStringExtra("collection");
        init();
        getListData();
    }

    public void init() {
        //收藏
        imvcollection = (ImageView) findViewById(R.id.imv_collection);
        if (("1").equals(Is_collection)) {
            imvcollection.setBackgroundResource(R.drawable.collection_pre_b);
        } else {
            imvcollection.setBackgroundResource(R.drawable.collection_b);
        }
        refreshLtxq.setColorSchemeColors(getResources().getColor(R.color.MainColor));
        refreshLtxq.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //数据刷新
                page = 1;
                getListData();
            }
        });
        linearLayoutManager = new LinearLayoutManager(this);
        rlistLtxq.setLayoutManager(linearLayoutManager);
        mAdapter = new PCXQAdapter(LunTanXQActivity.this, rlistLtxq, Temp_list, R.layout.item_luntan);
        //添加头部
        View headView = LayoutInflater.from(this).inflate(R.layout.header_luntan, rlistLtxq, false);
        imv_ltxq_userpic = (CircularImage) headView.findViewById(R.id.imv_ltxq_userpic);
        tv_ltxq_null = (TextView) headView.findViewById(R.id.tv_ltxq_null);
        tv_ltxq_title = (TextView) headView.findViewById(R.id.tv_ltxq_atitle);
        tv_ltxq_name = (TextView) headView.findViewById(R.id.tv_ltxq_name);
        tv_ltxq_dw = (TextView) headView.findViewById(R.id.tv_ltxq_dw);
        tv_ltxq_hfnum = (TextView) headView.findViewById(R.id.tv_ltxq_hfnum);
        li_ltheader_allhf = (LinearLayout) headView.findViewById(R.id.li_ltheader_allhf);
        tv_ltxq_content = (TextView) headView.findViewById(R.id.tv_ltxq_content);
        tv_ltxq_time = (TextView) headView.findViewById(R.id.tv_ltxq_time);
        li_allhf = (LinearLayout) headView.findViewById(R.id.li_allhf);
        //设置数据据
//        tv_ltxq_title.setText(getIntent().getStringExtra("title"));
//        tv_ltxq_name.setText(getIntent().getStringExtra("name"));
//        tv_ltxq_dw.setText(getIntent().getStringExtra("danwei"));
//        if (!TextUtils.isEmpty(getIntent().getStringExtra("hfnum"))) {
//            tv_ltxq_hfnum.setText(getIntent().getStringExtra("hfnum") + "个回复");
//        } else {
//            tv_ltxq_hfnum.setText("0个回复");
//        }
//        tv_ltxq_content.setText(getIntent().getStringExtra("content"));
//        tv_ltxq_time.setText(getIntent().getStringExtra("time"));
        ImgDataUtil.loadYuanImage(LunTanXQActivity.this, HttpIP.Base_IpIMage + getIntent().getStringExtra("url"), imv_ltxq_userpic);
        mAdapter.addHeadView(headView);
        rlistLtxq.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseLoadMoreHeaderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
            }
        });
        mAdapter.setOnLoadMoreListener(new BaseLoadMoreHeaderAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getListData();
            }
        });
    }

    /**
     * 论坛列表
     */
    private void getListData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.LunTanXQ, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("questionId", getIntent().getStringExtra("id"));
        mRequest.add("page", page);
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, LunTanXQM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        LunTanXQM model = ((LunTanXQM) data);
                        //头部数据
                        LunTanXQM.ObjectBean.QuestionBean question = model.getObject().getQuestion();
                        if(question!=null){
                        tv_ltxq_title.setText(model.getObject().getQuestion().getTitle());
                        tv_ltxq_name.setText(model.getObject().getQuestion().getUserName());
                        tv_ltxq_dw.setText(model.getObject().getQuestion().getCompName());
                        if (!TextUtils.isEmpty(model.getObject().getQuestion().getReplyCount() + "")) {
                            tv_ltxq_hfnum.setText(model.getObject().getQuestion().getReplyCount() + "个回复");
                        } else {
                            tv_ltxq_hfnum.setText("0个回复");
                        }
                        tv_ltxq_content.setText(model.getObject().getQuestion().getContent());
                        tv_ltxq_time.setText(model.getObject().getQuestion().getCreateDate());
                        ImgDataUtil.loadYuanImage(LunTanXQActivity.this, HttpIP.Base_IpIMage + model.getObject().getQuestion().getUserhead(), imv_ltxq_userpic);
                        }
                        LunTanXQM.ObjectBean.RepliesBean bean = new LunTanXQM.ObjectBean.RepliesBean();
                        bean.setCreateDate("1111");
                        bean.setNickName("");
                        bean.setRepContent("");
                        if (page == 1) {
                            Temp_list.clear();
                            Temp_list.add(bean);
                        }
                        if(model.getObject().getReplies()!=null){
                            Temp_list.addAll(model.getObject().getReplies());
                            Params.LTHF_num = (Temp_list.size() - 1) + "";
                            tv_ltxq_hfnum.setText((Temp_list.size() - 1) + "个回复");
                            if (Temp_list.size() == 1) {
                                li_ltheader_allhf.setVisibility(View.GONE);
                            } else {
                                li_ltheader_allhf.setVisibility(View.VISIBLE);
                            }

                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        refreshLtxq.setRefreshing(false);
                    }
                }, true, true);
    }

    /**
     * 论坛回复
     */
    private void getHfData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.HFLunTan, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("questionId", getIntent().getStringExtra("id"));
        mRequest.add("repContent", edLtxqHf.getText().toString());
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, CommonM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        CommonM model = ((CommonM) data);
                        page = 1;
                        getListData();
                        edLtxqHf.setText("");
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, false);
    }

    /**
     * 论坛赞
     */
    private void getZanData(String z_id, final int z_position) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Zan, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("replyId", z_id);
        mRequest.add("type", "1");
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, AddZanM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        AddZanM model = ((AddZanM) data);
                        Temp_list.get(z_position).setRepPraise(model.getObject().getRepPraise());
                        Temp_list.get(z_position).setIfPraise(model.getObject().getIfPraise());
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        CommonUtil.showToask(LunTanXQActivity.this, obj.getString("msg"));
                    }
                }, true, false);
    }

    /**
     * 论坛取消赞
     */
    private void getCancelZanData(String z_id, final int z_position) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.CancelZan, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("replyId", z_id);
        mRequest.add("type", "1");
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, AddZanM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        AddZanM model = ((AddZanM) data);
                        Temp_list.get(z_position).setRepPraise(model.getObject().getRepPraise());
                        Temp_list.get(z_position).setIfPraise(model.getObject().getIfPraise());
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        CommonUtil.showToask(LunTanXQActivity.this, obj.getString("msg"));
                    }
                }, true, false);
    }

    /**
     * 论坛收藏
     */
    private void getCollectionData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Collection, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("questionId", getIntent().getStringExtra("id"));
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, CommonM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        CommonM model = ((CommonM) data);
                        Is_collection = "1";
                        imvcollection.setBackgroundResource(R.drawable.collection_pre_b);
                        Params.Change_Collection = "1";
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        CommonUtil.showToask(LunTanXQActivity.this, obj.getString("msg"));
                    }
                }, true, false);
    }

    /**
     * 论坛取消收藏
     */
    private void getCancellCollectionData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.CancelCollection, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(LunTanXQActivity.this, "uid"));
        mRequest.add("questionId", getIntent().getStringExtra("id"));//取消论坛时   传questionID  取消知识是  传CourseID
        CallServer.getRequestInstance().add(LunTanXQActivity.this, 0, mRequest,
                new CustomHttpListener(LunTanXQActivity.this, true, CommonM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        CommonM model = ((CommonM) data);
                        Is_collection = "0";
                        imvcollection.setBackgroundResource(R.drawable.collection_b);
                        Params.Change_Collection = "0";
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        CommonUtil.showToask(LunTanXQActivity.this, obj.getString("msg"));
                    }
                }, true, false);
    }

    public class PCXQAdapter extends BaseLoadMoreHeaderAdapter<LunTanXQM.ObjectBean.RepliesBean> {


        public PCXQAdapter(Context mContext, RecyclerView recyclerView, List<LunTanXQM.ObjectBean.RepliesBean> mDatas, int mLayoutId) {
            super(mContext, recyclerView, mDatas, mLayoutId);
        }

        @Override
        public void convert(Context mContext, final RecyclerView.ViewHolder holder, final LunTanXQM.ObjectBean.RepliesBean s) {
            CircularImage pic = (CircularImage) holder.itemView.findViewById(R.id.imv_lt_userpic);
            TextView name = (TextView) holder.itemView.findViewById(R.id.tv_lt_name);
            TextView danwei = (TextView) holder.itemView.findViewById(R.id.tv_lt_dw);
            TextView tv_lt_hfnum = (TextView) holder.itemView.findViewById(R.id.tv_lt_hfnum);
            TextView tv_content = (TextView) holder.itemView.findViewById(R.id.tv_lt_content);
            TextView tv_lt_titkle = (TextView) holder.itemView.findViewById(R.id.tv_lt_titkle);
            TextView time = (TextView) holder.itemView.findViewById(R.id.tv_lt_time);
            LinearLayout li_lt_zan = (LinearLayout) holder.itemView.findViewById(R.id.li_lt_zan);
            ImageView imv_lt_zan = (ImageView) holder.itemView.findViewById(R.id.imv_lt_zan);
            TextView tv_lt_zannum = (TextView) holder.itemView.findViewById(R.id.tv_lt_zannum);
            LinearLayout li_lt_hf = (LinearLayout) holder.itemView.findViewById(R.id.li_lt_hf);
            View view_hf_top = (View) holder.itemView.findViewById(R.id.view_hf_top);
            LinearLayout li_man = (LinearLayout) holder.itemView.findViewById(R.id.li_lt_man);
            LinearLayout li_danwei = (LinearLayout) holder.itemView.findViewById(R.id.li_danwei);
            li_danwei.setVisibility(View.GONE);
            li_lt_hf.setVisibility(View.GONE);
            view_hf_top.setVisibility(View.GONE);
            tv_lt_titkle.setVisibility(View.GONE);
            li_lt_zan.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams para = pic.getLayoutParams();
            para.height = CommonUtil.dip2px(LunTanXQActivity.this, 35);
            para.width = CommonUtil.dip2px(LunTanXQActivity.this, 35);
            pic.setLayoutParams(para);
            ImgDataUtil.loadYuanImage(LunTanXQActivity.this, HttpIP.Base_IpIMage + s.getUserhead(), pic);
            name.setText(s.getUserName());
            tv_content.setText(s.getRepContent());
            time.setText(s.getCreateDate());
            if (s.getIfPraise() == 1) {
                imv_lt_zan.setBackgroundResource(R.drawable.bbs_zan_pre_b);
            } else {
                imv_lt_zan.setBackgroundResource(R.drawable.bbs_zan_b);
            }
            tv_lt_zannum.setText(s.getRepPraise() + "");
            if (holder.getLayoutPosition() == Temp_list.size() - 1) {
                li_man.setVisibility(View.GONE);
            } else {
                li_man.setVisibility(View.VISIBLE);
            }
            //赞
            li_lt_zan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (s.getIfPraise() == 0) {
                        getZanData(s.getReplyId(), holder.getLayoutPosition());
                    } else {
                        getCancelZanData(s.getReplyId(), holder.getLayoutPosition());
                    }
                }
            });
        }
    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ltxq_fs://发送
                if (TextUtils.isEmpty(edLtxqHf.getText().toString())) {
                    CommonUtil.showToask(LunTanXQActivity.this, "请输入回复内容！");
                    return;
                }
                getHfData();
                break;
            case R.id.imv_collection://收藏
                if (("1").equals(Is_collection)) {
                    getCancellCollectionData();
                } else {
                    getCollectionData();
                }
                break;
        }
    }
}
